<template>
  <div class="app-container">
    <ShortCut></ShortCut>
    <toubu @type-selected="updateGoodsList"></toubu>
    <nav class="main-nav">
      <div class="main-nav" id="J_main_nav">
        <div class="head-inner">
          <ul class="main-nav-link clearfix" id="J_main_nav_link">
            <li class="">
              <a class="main-nav-atag menu-item-isbold" mars_sead="home_header_channel_myi">我的唯品会</a>
            </li>
            <li class="">
              <a class="main-nav-atag nav_current" mars_sead="home_header_channel_safe">安全中心</a>
            </li>
            <li class="nav-comingsoon">
              <a class="main-nav-atag" mars_sead="home_header_channel_user_forecast">我的特卖</a>
            </li>
            <li class="nav-category">
              <a class="main-nav-atag" mars_sead="home_header_channel_user_classicfy" href="/home">首页</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>
    
    <div class="user-profile-container">
      <!-- 左侧导航 -->
      <div class="profile-sidebar">
        <div class="avatar-upload">
          <img :src="avatarUrl || defaultAvatar" class="avatar-preview">
          <input type="file" @change="handleAvatarChange" accept="image/*" ref="avatarInput" style="display: none;">
          <button @click="$refs.avatarInput.click()" class="upload-btn">更换头像</button>
        </div>
        <ul class="profile-menu">
          <li class="active">基本资料</li>
          <li>尺码信息</li>
          <li>隐私设置</li>
        </ul>
      </div>
      
      <!-- 右侧内容 -->
      <div class="profile-content">
        <h2>基本资料</h2>
        <div class="profile-info">
          <p class="welcome">唯品会会员（{{ username }}）</p>
          <p class="completeness">资料完整度：{{ profileCompleteness }}%</p>
          
          <div class="form-group">
            <label>登录名：</label>
            <span class="hint">立即设置（为账号打上独一无二的个人标记）</span>
          </div>
          
          <div class="form-group">
            <label>昵称：</label>
            <input type="text" v-model="nickname">
            <button @click="updateNickname" class="save-btn">保存</button>
          </div>
          
          <div class="form-group">
            <label>性别：</label>
            <label><input type="radio" v-model="gender" value="male"> 男</label>
            <label><input type="radio" v-model="gender" value="female"> 女</label>
          </div>
          
          <!-- <div class="form-group">
            <label>生日：</label>
            <select v-model="birthYear">
              <option value="">请选择</option>
              <option v-for="year in years" :value="year">{{ year }}年</option>
            </select>
            <select v-model="birthMonth">
              <option value="">请选择</option> 
              <option v-for="month in 12" :value="month">{{ month }}月</option>
            </select>
            <select v-model="birthDay">
              <option value="">请选择</option>
              <option v-for="day in daysInMonth" :value="day">{{ day }}日</option>
            </select>
            <span class="hint">填写可享生日礼包哦~</span>
          </div> -->
          
          <div class="form-group">
            <label>移动电话：</label>
            <span>155****752（已验证）</span>
            <a href="#" class="modify-link">修改</a>
          </div>
          
          <div class="form-group">
            <label>邮箱：</label>
            <a href="#" class="modify-link">修改</a>
          </div>
          
          <div class="password-change">
            <h3>修改密码</h3>
            <div class="form-group">
              <label>当前密码：</label>
              <input type="password" v-model="currentPassword" placeholder="请输入当前密码">
            </div>
            <div class="form-group">
              <label>新密码：</label>
              <input type="password" v-model="newPassword" placeholder="8位以上，含数字和英文">
            </div>
            <div class="form-group">
              <label>确认密码：</label>
              <input type="password" v-model="confirmPassword" placeholder="再次输入新密码">
            </div>
            <button @click="changePassword" class="submit-btn">提交</button>
            <button @click="resetForm" class="reset-btn">重置</button>
            <p v-if="passwordError" class="error-message">{{ passwordError }}</p>
            <p v-if="passwordSuccess" class="success-message">{{ passwordSuccess }}</p>
          </div>
        </div>
      </div>
    </div>
    
    <Footer></Footer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import ShortCut from "@/components/common/ShortCut.vue";
import toubu from "@/components/common/toubu.vue";
import Footer from "@/components/common/Footer.vue";


const avatarUrl = ref("");
const username = ref("vip*****lee");
const nickname = ref("唯品会会员");
const gender = ref("");
const birthYear = ref("");
const birthMonth = ref("");
const birthDay = ref("");
const currentPassword = ref("");
const newPassword = ref("");
const confirmPassword = ref("");
const passwordError = ref("");
const passwordSuccess = ref("");
const profileCompleteness = ref(5);

// 生成年份选项
const currentYear = new Date().getFullYear();
const years = Array.from({length: 100}, (_, i) => currentYear - i);

// 计算当月天数
const daysInMonth = computed(() => {
  if (!birthYear.value || !birthMonth.value) return 31;
  return new Date(birthYear.value, birthMonth.value, 0).getDate();
});

onMounted(() => {
  // 从sessionStorage获取用户信息
  const storedUsername = sessionStorage.getItem("userName");
  if (storedUsername) {
    username.value = storedUsername;
  }
});

// 头像上传处理
const handleAvatarChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      avatarUrl.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

// 更新昵称
const updateNickname = () => {
  if (!nickname.value.trim()) {
    alert("昵称不能为空");
    return;
  }
  alert("昵称更新成功");
};

const changePassword = async () => {
  // 重置错误和成功消息
  passwordError.value = "";
  passwordSuccess.value = "";

  // 验证当前密码是否为空
  if (!currentPassword.value) {
    passwordError.value = "请输入当前密码";
    return;
  }

  // 验证新密码格式
  const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
  if (!passwordRegex.test(newPassword.value)) {
    passwordError.value = "密码必须8位以上，包含数字和英文";
    return;
  }

  // 验证两次输入一致
  if (newPassword.value !== confirmPassword.value) {
    passwordError.value = "两次输入的密码不一致";
    return;
  }

  try {
    // 获取存储的用户信息
    const userId = sessionStorage.getItem("userId");
    const username = sessionStorage.getItem("userName");

    // 验证用户是否登录
    if (!userId || !username) {
      passwordError.value = "用户未登录，请重新登录";
      return;
    }

    // 1. 获取用户数据
    const userRes = await axios.get("http://127.0.0.1:3000/api/user/getAllUsers");
    
    // 2. 查找当前用户
    const currentUser = userRes.data.data.find(user => {
      // 检查ID字段（兼容不同命名）
      const idMatch = user.id == userId || 
                     user.userId == userId || 
                     user._id == userId;
      
      // 检查用户名字段（兼容不同命名）
      const nameMatch = user.username === username || 
                       user.uname === username ||
                       user.name === username;
      
      return idMatch && nameMatch;
    });

    if (!currentUser) {
      passwordError.value = "用户信息获取失败，请检查登录状态";
      return;
    }

    // 3. 获取存储的密码（兼容不同字段名）
    const storedPassword = currentUser.userpasswd || 
                         currentUser.password || 
                         currentUser.upass;
    
    if (!storedPassword) {
      passwordError.value = "系统错误：无法验证密码";
      return;
    }

    // 4. 验证当前密码是否匹配
    if (storedPassword !== currentPassword.value) {
      passwordError.value = "当前密码输入错误";
      return;
    }

    // 5. 密码验证通过，更新密码
    const response = await axios.post("http://127.0.0.1:3000/api/user/updateUser", {
      id: userId,
      uname: username,
      upass: newPassword.value,
    });

    if (response.data.status === 0) {
      passwordSuccess.value = "密码修改成功";

      // 3秒后清空成功消息和表单
      setTimeout(() => {
        passwordSuccess.value = "";
        resetForm();
      }, 3000);
    } else {
      passwordError.value = response.data.message || "密码修改失败";
    }
  } catch (error) {
    console.error("修改密码失败:", error);
    
    // 更详细的错误处理
    if (error.response) {
      passwordError.value = `服务器错误: ${error.response.data.message || error.response.status}`;
    } else if (error.request) {
      passwordError.value = "无法连接到服务器，请检查网络连接";
    } else {
      passwordError.value = "请求配置错误: " + error.message;
    }
  }
};
// 重置表单
const resetForm = () => {
  currentPassword.value = "";
  newPassword.value = "";
  confirmPassword.value = "";
  passwordError.value = "";
};
</script>

<style lang="scss" scoped>
/* 原有导航样式保持不变 */
.main-nav {
  clear: both;
  position: relative;
  height: 40px;
  line-height: 40px;
  background-color: #f10180;
  font-size: 14px;
  color: #fff;
}
.head-inner {
  width: 1000px;
  margin: 0 auto;
  position: relative;
  clear: both;
}
.main-nav-link .main-nav-atag {
    display: block;
    height: 40px;
    _height: auto;
    padding: 0 14px;
    text-align: center;
    color: #fff;
    _width: 80px;
    _padding: 0;
    font-size: 16px;
    white-space: nowrap;
}
.main-nav-link .nav-category, .main-nav-link .nav-comingsoon {
    float: right;
}
.header ul {
    margin: 0;
    padding: 0;
}
.header li {
    list-style: none;
}
.main-nav-link li {
    float: left;
    position: relative;
    z-index: 8;
}

/* 个人中心样式 */
.user-profile-container {
  width: 1000px;
  margin: 20px auto;
  display: flex;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.profile-sidebar {
  width: 200px;
  padding: 20px;
  background: #f8f8f8;
  border-right: 1px solid #eee;
}

.avatar-upload {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 10px;
  border: 2px solid #f10180;
}

.upload-btn {
  background: #f10180;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.profile-menu li {
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.profile-menu li.active {
  color: #f10180;
  font-weight: bold;
}

.profile-content {
  flex: 1;
  padding: 20px;
}

.welcome {
  font-size: 18px;
  color: #333;
  margin-bottom: 5px;
}

.completeness {
  color: #999;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.form-group label {
  width: 80px;
  text-align: right;
  margin-right: 10px;
}

.form-group input, .form-group select {
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 3px;
  margin-right: 10px;
}

.hint {
  color: #999;
  font-size: 12px;
}

.modify-link {
  color: #f10180;
  text-decoration: none;
  margin-left: 10px;
  font-size: 12px;
}

.save-btn, .submit-btn {
  background: #f10180;
  color: white;
  border: none;
  padding: 5px 15px;
  border-radius: 3px;
  cursor: pointer;
}

.reset-btn {
  background: #ddd;
  color: #333;
  border: none;
  padding: 5px 15px;
  border-radius: 3px;
  cursor: pointer;
  margin-left: 10px;
}

.password-change {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.error-message {
  color: red;
  margin-top: 10px;
}

.success-message {
  color: green;
  margin-top: 10px;
}
</style>